import React, { Component } from 'react';
import PropTypes from "prop-types";
import {
    StyleSheet,
    Image,
    View,
    TouchableHighlight,
    TouchableOpacity,
    Platform,
    Dimensions
} from 'react-native';

import Label from '../label';
import Color from '../../config/theme/standard/color';

const CB_ENABLED_IMAGE_LEFT = require('../../assets/checkBox_enabled_left.png');
const CB_DISABLED_IMAGE_LEFT = require('../../assets/checkBox_disabled_left.png');
const CB_ENABLED_IMAGE_LEFT_GRAY = require('../../assets/checkBox_enabled_left_gray.png');
const CB_DISABLED_IMAGE_LEFT_GRAY = require('../../assets/checkBox_disabled_left_gray.png');

const CB_ENABLED_IMAGE_RIGHT = require('../../assets/checkBox_enabled_right.png');
const CB_DISABLED_IMAGE_RIGHT = require('../../assets/checkBox_disabled_right.png');
const CB_ENABLED_IMAGE_RIGHT_GRAY = require('../../assets/checkBox_enabled_right_gray.png');
const CB_DISABLED_IMAGE_RIGHT_GRAY = require('../../assets/checkBox_disabled_right_gray.png');

const CB_ENABLED_IMAGE_AGREEMENT = require('../../assets/checkBox_enabled_agreement.png');
const CB_DISABLED_IMAGE_AGREEMENT = require('../../assets/checkBox_disabled_agreement.png');

export default class CheckBox extends Component {
    constructor(props) {
        super(props);

        this.state = {
            prevPropsInternalChecked: props.isChecked,
            internalChecked: props.isChecked, //初始选择状态
            isDisabled: props.disabled, //是否禁用
            isWideScreen: false // 鸿蒙适配是否宽屏
        };
    }

    componentDidMount() {
        // 适配鸿蒙折叠屏动态更新组件
        this.addEventListenerScreenWidth = Dimensions.addEventListener('change', this.setIsWideScreen)
    }
    componentWillUnmount() {
        // 适配鸿蒙折叠屏动态更新组件
        if (this.addEventListenerScreenWidth) {
            this.addEventListenerScreenWidth = null
        }
    }
    setIsWideScreen = () => {
        const screenWidth = Dimensions.get('window').width;
        if (screenWidth) {
            this.setState({
                isWideScreen: screenWidth > 500 && screenWidth < 800
            })
        }
    }

    onChange = () => {
        if (Platform.OS == "web" && this.props.disabled) {
            return
        }
        let internalChecked = this.state.internalChecked;
        let newState = !internalChecked;

        if (this.props.onChange) {
            this.props.onChange(newState, this.props.value);
        }
        this.setState({
            internalChecked: newState
        });
    };


    static getDerivedStateFromProps(nextProps, prevState) {
        if (('isChecked' in nextProps) && (nextProps.isChecked !== prevState.prevPropsInternalChecked)) {
            return {
                prevPropsInternalChecked: nextProps.isChecked,
                internalChecked: nextProps.isChecked,
            };
        }
        return null;
    }

    render() {
        const screenWidth = Dimensions.get('window').width;
        const { label, desc, labelBefore, labelLines, hasIcon, source, disabled, fontSize, color, size, children, widthFlag, widthLabel } = this.props;

        let container;
        let sourceLeft;
        let sourceLeftDisabled;
        let sourceRight;
        let sourceRightDisabled;
        let sourceAgreement;

        const containerSyles = [styles.container];
        const labelRightStyles = [styles.labelRight];
        const labelLeftStyles = [styles.labelLeft];
        const checkboxLeftStyles = [styles.checkboxLeft, Platform.OS == 'harmony' &&{ zIndex:1 }];
        const checkboxRightStyles = [styles.checkboxRight, Platform.OS == 'harmony' &&{ zIndex:1 }];
        const iconStyles = [styles.icon, Platform.OS == 'harmony' &&{ zIndex:1 }];
        const labelContainerRightStyles = [styles.labelContainerRight];
        const labelContainerLeftStyles = [styles.labelContainerLeft];

        switch (size) {
            case 'normal':
                break;
            case 'agreement':
                checkboxLeftStyles.push({ width: 15, height: 15 });
                break;
            default:
                break;
        };
        if (widthFlag == "0") {
            labelContainerRightStyles.push({ width: screenWidth - 15 - 49 });
        } else if (widthFlag == "1") {
            labelContainerRightStyles.push({ width: widthLabel });
        };

        if (color) {
            labelRightStyles.push({ color: color });
            labelLeftStyles.push({ color: color });
        }

        if (fontSize) {
            labelRightStyles.push({ fontSize: fontSize });
            labelLeftStyles.push({ fontSize: fontSize });
        }

        //复选样式一（图片）
        //Enabled
        if (typeof this.props.checked === 'boolean') {
            sourceLeft = this.props.checked ? this.props.checkedImageLeft : this.props.uncheckedImageLeft;
            sourceAgreement = this.props.checked ? this.props.checkedImageAgreement : this.props.uncheckedImageAgreement;
        } else {
            sourceLeft = this.state.internalChecked ? this.props.checkedImageLeft : this.props.uncheckedImageLeft;
            sourceAgreement = this.state.internalChecked ? this.props.checkedImageAgreement : this.props.uncheckedImageAgreement;
        }
        //Disabled
        if (typeof this.props.checked === 'boolean') {
            sourceLeftDisabled = this.props.checked ? this.props.disabledCheckedImageLeft : this.props.disabledUncheckedImageLeft;
        } else {
            sourceLeftDisabled = this.state.internalChecked ? this.props.disabledCheckedImageLeft : this.props.disabledUncheckedImageLeft;
        }

        //复选样式二（图片）
        //Enabled
        if (typeof this.props.checked === 'boolean') {
            sourceRight = this.props.checked ? this.props.checkedImageRight : this.props.uncheckedImageRight;
        } else {
            sourceRight = this.state.internalChecked ? this.props.checkedImageRight : this.props.uncheckedImageRight;
        }
        //Disabled
        if (typeof this.props.checked === 'boolean') {
            sourceRightDisabled = this.props.checked ? this.props.disabledCheckedImageRight : this.props.disabledUncheckedImageRight;
        } else {
            sourceRightDisabled = this.state.internalChecked ? this.props.disabledCheckedImageRight : this.props.disabledUncheckedImageRight;
        }

        let icon = null;

        if (hasIcon) {
            icon = (<Image style={iconStyles} source={source} />);
            labelContainerRightStyles.push({ width: screenWidth - 15 - 49 - 28 - 12, marginLeft: 55 });
        }

        if (labelBefore) {
            //复选样式二
            container = (
                <View style={styles.container}>
                    {icon}
                    {(label ? (
                        <View style={labelContainerRightStyles}>
                            <Label text={label} numberOfLines={labelLines} type={'button'} color={'normal'} />
                            {desc ?
                                <Label text={desc} type={'percent'} labelStyle={{ color: '#666', marginTop: 5 }} numberOfLines={1} />
                                : null}
                        </View>
                    ) : <View />)}
                    {(children ? (
                        <View style={labelContainerRightStyles}>
                            {children}
                        </View>
                    ) : <View />)}

                    <Image style={checkboxRightStyles} source={disabled ? sourceRightDisabled : sourceRight} />
                </View>
            );
        } else {
            //复选样式一
            if (size == 'normal') {
                labelContainerLeftStyles.push({ width: screenWidth - 15 - 49 });
                container = (
                    <View style={styles.container}>
                        <Image style={checkboxLeftStyles} source={disabled ? sourceLeftDisabled : sourceLeft} />
                        {(label ? (
                            <View style={labelContainerLeftStyles}>
                                <Label text={label} numberOfLines={labelLines} type={fontSize ? fontSize : 'button'} color={color} />
                                {desc ?
                                    <Label text={desc} type={'percent'} labelStyle={{ color: '#666', marginTop: 5 }} numberOfLines={1} />
                                    : null}
                            </View>
                        ) : <View />)}
                    </View>
                );
            } else if (size == 'agreement') {
                container = (
                    <View style={{ flexDirection: 'row' }}>
                        <Image style={{ width: 16, height: 16, marginLeft: 15, marginRight: 6, marginTop: 2, resizeMode: 'contain' }} source={sourceAgreement} />
                        <View style={{ width: screenWidth - 15 - 37 }}>
                            {children}
                        </View>
                    </View>
                )
            }

        }
        let resultCom = null;
        if (Platform.OS == "web") {
            resultCom = <TouchableOpacity
                activeOpacity={0.7}
                underlayColor={this.props.size == 'normal' ? Color.icon.disable : 'transparent'}
                onClick={this.onChange}
                disabled={disabled}
                isChecked={this.state.internalChecked}
            >
                {container}
            </TouchableOpacity>
        } else {
            resultCom = <TouchableOpacity activeOpacity={0.7}
                underlayColor={this.props.size == 'normal' ? Color.icon.disable : 'transparent'}
                onPress={this.onChange}
                disabled={disabled}
                isChecked={this.state.internalChecked}
            >
                {container}
            </TouchableOpacity>
        }

        return (
            <View>
                {resultCom}
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        alignItems: 'center',
        minHeight: 44,
        position: 'relative',
        paddingVertical: 12,
    },
    //复选样式一
    checkboxLeft: {
        width: 28,
        height: 28,
        position: 'absolute',
        left: 15,
        top: 8,
        overflow: 'hidden',
        resizeMode: 'contain'
    },
    labelContainerLeft: {
        marginLeft: 49
    },

    //复选样式二
    checkboxRight: {
        width: 28,
        height: 28,
        position: 'absolute',
        top: 8,
        right: 15,
        overflow: 'hidden',
        resizeMode: 'contain'
    },
    labelContainerRight: {
        marginLeft: 15
    },
    icon: {
        width: 28,
        height: 28,
        position: 'absolute',
        left: 15,
        top: 8,
        overflow: 'hidden',
        resizeMode: 'contain'
    }
});

CheckBox.propTypes = {
    label: PropTypes.string.isRequired,
    value: PropTypes.string,
    desc: PropTypes.string,
    isChecked: PropTypes.bool,
    labelBefore: PropTypes.bool,
    labelLines: PropTypes.number,
    disabled: PropTypes.bool,
    hasIcon: PropTypes.bool,
    source: PropTypes.any,
    color: PropTypes.oneOf(['description', 'fill', 'assist', 'link', 'error', 'increase', 'decrease', 'navbar', 'main', 'disable', 'white', 'normal', 'black']),
    fontSize: PropTypes.oneOf(['header', 'title', 'secTitle', 'button', 'form', 'description', 'percent', 'bottom']),
    size: PropTypes.oneOf(['normal', 'agreement']),
    checked: PropTypes.bool,
    onChange: PropTypes.func,
    isChange: PropTypes.bool,
    widthFlag: PropTypes.string
};

CheckBox.defaultProps = {
    label: '',
    isChecked: false,
    labelBefore: false,
    labelLines: 1,
    checked: null,
    disabled: false,
    hasIcon: false,
    color: 'normal',
    fontSize: 'button',
    size: 'normal',
    //复选样式一
    checkedImageLeft: CB_ENABLED_IMAGE_LEFT,  //选中状态
    uncheckedImageLeft: CB_DISABLED_IMAGE_LEFT,  //未选中状态
    disabledCheckedImageLeft: CB_ENABLED_IMAGE_LEFT_GRAY,  //选中状态禁用
    disabledUncheckedImageLeft: CB_DISABLED_IMAGE_LEFT_GRAY,  //未选中状态禁用
    //复选样式二
    checkedImageRight: CB_ENABLED_IMAGE_RIGHT,  //选中状态
    uncheckedImageRight: CB_DISABLED_IMAGE_RIGHT,  //未选中状态
    disabledCheckedImageRight: CB_ENABLED_IMAGE_RIGHT_GRAY,  //选中状态禁用
    disabledUncheckedImageRight: CB_DISABLED_IMAGE_RIGHT_GRAY,  //未选中状态禁用
    //协议勾选
    checkedImageAgreement: CB_ENABLED_IMAGE_AGREEMENT, //协议选中
    uncheckedImageAgreement: CB_DISABLED_IMAGE_AGREEMENT, //协议未选中
    isChange: false,
    widthFlag: '0'
};